#include <stdio.h>
#include <unistd.h>
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "iot_gpio.h"
#include "hi_gpio.h"
#include "hi_io.h"

#define KEY_GPIO  HI_GPIO_IDX_14 // ax100  

// 假设三色灯分别连接到以下三个 GPIO 引脚
#define RED_LED_GPIO  HI_GPIO_IDX_2
#define GREEN_LED_GPIO HI_GPIO_IDX_7
#define BLUE_LED_GPIO HI_GPIO_IDX_8

IotGpioValue g_redLedValue = IOT_GPIO_VALUE0;
IotGpioValue g_greenLedValue = IOT_GPIO_VALUE0;
IotGpioValue g_blueLedValue = IOT_GPIO_VALUE0;

int g_keyJitterFlag = 0;
int g_ledState = 0; // 用于记录当前灯的状态

void KeyISR( char *arg){
    if (g_keyJitterFlag == 1){
        return;
    }
   
    printf("Key Down\r\n");

    switch (g_ledState) {
        case 0:
            g_redLedValue = IOT_GPIO_VALUE1;
            g_greenLedValue = IOT_GPIO_VALUE0;
            g_blueLedValue = IOT_GPIO_VALUE0;
            printf("Red Led On\r\n");
            break;
        case 1:
            g_redLedValue = IOT_GPIO_VALUE0;
            g_greenLedValue = IOT_GPIO_VALUE1;
            g_blueLedValue = IOT_GPIO_VALUE0;
            printf("Green Led On\r\n");
            break;
        case 2:
            g_redLedValue = IOT_GPIO_VALUE0;
            g_greenLedValue = IOT_GPIO_VALUE0;
            g_blueLedValue = IOT_GPIO_VALUE1;
            printf("Blue Led On\r\n");
            break;
        case 3:
            g_redLedValue = IOT_GPIO_VALUE0;
            g_greenLedValue = IOT_GPIO_VALUE0;
            g_blueLedValue = IOT_GPIO_VALUE0;
            printf("All Leds Off\r\n");
            break;
    }

    g_ledState = (g_ledState + 1) % 4; // 循环切换状态

    g_keyJitterFlag = 1;
}

static void GpioKeyMain( void ) {
    // 初始化红色 LED
    hi_io_set_func(RED_LED_GPIO, HI_IO_FUNC_GPIO_8_GPIO);
    IoTGpioInit( RED_LED_GPIO );
    IoTGpioSetDir( RED_LED_GPIO, IOT_GPIO_DIR_OUT );

    // 初始化绿色 LED
    hi_io_set_func(GREEN_LED_GPIO, HI_IO_FUNC_GPIO_9_GPIO);
    IoTGpioInit( GREEN_LED_GPIO );
    IoTGpioSetDir( GREEN_LED_GPIO, IOT_GPIO_DIR_OUT );

    // 初始化蓝色 LED
    hi_io_set_func(BLUE_LED_GPIO, HI_IO_FUNC_GPIO_10_GPIO);
    IoTGpioInit( BLUE_LED_GPIO );
    IoTGpioSetDir( BLUE_LED_GPIO, IOT_GPIO_DIR_OUT );

    // 初始化按键
    hi_io_set_func(KEY_GPIO, HI_IO_FUNC_GPIO_14_GPIO);
    IoTGpioInit( KEY_GPIO );
    IoTGpioSetDir( KEY_GPIO, IOT_GPIO_DIR_IN );
    IoTGpioRegisterIsrFunc( KEY_GPIO, IOT_INT_TYPE_EDGE, IOT_GPIO_EDGE_FALL_LEVEL_LOW, KeyISR, NULL );
    IoTGpioSetIsrMask( KEY_GPIO, 0 );

    printf("IoT-LedKey Init OK\r\n");
    while (1) {
        g_keyJitterFlag = 0;

        IoTGpioSetOutputVal( RED_LED_GPIO, g_redLedValue );
        IoTGpioSetOutputVal( GREEN_LED_GPIO, g_greenLedValue );
        IoTGpioSetOutputVal( BLUE_LED_GPIO, g_blueLedValue );

        osDelay( 50 );
    }

    return ;
}

SYS_RUN( GpioKeyMain );